package com.sk.weichat.ui.circle;

import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.sk.weichat.R;
import com.sk.weichat.adapter.DynamicMultiItemAdapter;
import com.sk.weichat.bean.DynamicBean;
import com.sk.weichat.bean.circle.PublicMessage;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.MediaPlayerHelper;
import com.sk.weichat.util.ScreenUtil;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.view.DynamicShortVideoControlView;
import com.sk.weichat.view.MyHeader;
import com.sk.weichat.view.RecycleViewDivider;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * @author lzs
 * @date 2019/10/31
 * Email:343067508@qq.com
 **/
public class TopicDynamicActivity extends BaseActivity implements DynamicShortVideoControlView.VideoViewController, TextureView.SurfaceTextureListener, MediaPlayerHelper.MediaPlayerListener {
    static final int PAGE_SIZE = 10;
    String topicName = "";
    DynamicMultiItemAdapter adapter;
    List<DynamicBean> data = new ArrayList<>();
    SmartRefreshLayout refreshLayout;
    TextView tvName;//创建者名称
    TextView tvCount;// 动态名称
    SimpleDraweeView ivAvatar; //创建者头像
    LinearLayoutManager layoutManager;
    RecyclerView recyclerView;
    // int top; //顶部的距离
    int bottom; //底部的距离
    DynamicBean playingVideoDynamicBean;

    private TextureView textureView;
    //private PlayTextureView playTextureView;
    private DynamicShortVideoControlView controlView;
    private CoordinatorLayout rootContainer;
    SurfaceTexture surfaceTexture;
    DecimalFormat decimalFormat = new DecimalFormat("00");
    ConstraintLayout videoView;
    AppBarLayout appBarLayout;
    Toolbar toolbar;

    int offsetAppbar;//appbar滑动的距离
    private final static int updateProgressMsg = 19;
    private final int updateProgress_alternation = 200;//毫秒更新一次进度条

    ImageView ivDrop;//滑动背景图片
    boolean isDown = false;
    private Handler progressTimer = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
                long duration = MediaPlayerHelper.getInstance().getDuration();
                long current = MediaPlayerHelper.getInstance().getCurrentPosition();
                //Log.e("lzs", "duration:" + duration + "  current:" + current);
                updateProgressAndTime(duration, current);
            }
            startProgressUpdateTimer();
            return true;
        }
    });

    private String formatVideoDuration(long duration) {
        int time = Math.round(duration * 1.0f / 1000);
        int second = time % 60;
        int minute = time / 60;
        int hour = time % 60 / 60;
        return (hour == 0 ? "" : decimalFormat.format(hour) + ":") + decimalFormat.format(minute) + ":" + decimalFormat.format(second);
    }

    private void updateProgressAndTime(long duration, long progress) {
        if (controlView != null) {
            controlView.updateProgress(duration, progress);
            controlView.setTime(formatVideoDuration(duration) + "''");
        }
    }

    /**
     * 开始进度条更新计时器
     */
    private void startProgressUpdateTimer() {
        if (progressTimer != null) {
            progressTimer.removeMessages(updateProgressMsg);
            progressTimer.sendEmptyMessageDelayed(updateProgressMsg, updateProgress_alternation);
        }
    }

    /**
     * 停止进度条更新计时器
     */
    private void stopProgressUpdateTimer() {
        if (progressTimer != null) {
            progressTimer.removeMessages(updateProgressMsg);
        }
    }

    private void addVideoView() {
        if (videoView != null) {
            rootContainer.removeView(videoView);
        }
        videoView = initVideoView();
        rootContainer.addView(videoView, 1);
    }

    private void preparePlay() {
        if (playingVideoDynamicBean.getBody().getVideos() == null || playingVideoDynamicBean.getBody().getVideos().size() == 0) {
            return;
        }
        PublicMessage.Resource video = playingVideoDynamicBean.getBody().getVideos().get(0);
        //Log.e("lzs", "prepare url:" + video.getOriginalUrl());
        if (!video.getOriginalUrl().equalsIgnoreCase(MediaPlayerHelper.getInstance().getCurrentUrl())) {
            try {
                MediaPlayerHelper.getInstance().prepare(surfaceTexture, video.getOriginalUrl(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_pause) {
            //相同的播放地址，且是暂停状态，重新播放
            //Log.e("lzs", "prepare  change" + surfaceTexture.hashCode());
            MediaPlayerHelper.getInstance().start();
        }

    }

    public static final void startTopicDynamicActivity(Context context, String topicName) {
        Intent intent = new Intent(context, TopicDynamicActivity.class);
        intent.putExtra("topicName", topicName);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_dynamic);
        //浅色状态栏文字
        StatusBarCompat.setLightStatusBar(getWindow(), false);

        findViewById(R.id.iv_add_dynamic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转发动态页面
                startActivity(new Intent(mContext, PublishDynamicActivity.class).putExtra("flag", 3));
            }
        });

        rootContainer = findViewById(R.id.container);
        topicName = getIntent().getStringExtra("topicName");
        toolbar = findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setTitle("#" + topicName + "#");
        ivDrop = findViewById(R.id.iv_drop);

        tvName = findViewById(R.id.tv_name);
        tvCount = findViewById(R.id.tv_count);
        ivAvatar = findViewById(R.id.iv_avatar);
        appBarLayout = findViewById(R.id.appbar);
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            int max = ViewPiexlUtil.dp2px(mContext, 50);
            int current;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                if (current != i) {
                    current = i;
                } else {
                    return;
                }
                offsetAppbar -= i;
                float alpha = 0;
                if (i + max < 0) {
                    alpha = 0;
                } else {
                    alpha = 1 + i * 1.0f / max;
                }
                tvCount.setAlpha(Math.abs(alpha));
                tvName.setAlpha(Math.abs(alpha));
                ivAvatar.setAlpha(Math.abs(alpha));
                adjustAtciveItem();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (firstVisibleItemPosition < 0 || lastVisibleItemPosition < 0) {
                    return;
                }
                Log.e("lzs", "111");
                View target = findActiveTarget(findActiveVideoPos(firstVisibleItemPosition, lastVisibleItemPosition), layoutManager);
                if (null != target) {
                    attachVideoViewTo(target);
                } else {
                    if (textureView != null) {
                        textureView.setVisibility(View.GONE);
                    }
                    if (controlView != null) {
                        controlView.setVisibility(View.GONE);
                    }
                }
            }
        });

        recyclerView = findViewById(R.id.recyclerview);
        //禁止默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        RecycleViewDivider divider = new RecycleViewDivider(mContext, 0, ViewPiexlUtil.dp2px(mContext, 8), getResources().getColor(R.color.color_bg_f5f7fa));
        recyclerView.addItemDecoration(divider);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new DynamicMultiItemAdapter(data);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.container && data.get(position).getItemType() == DynamicBean.type_short_video) {
                    //Log.e("lzs", "position:" + position + "   data:" + data.get(position));
                    //跳转视频详情
                    DynamicVideoDetailsActivity2.startDynamicVideoDetailsActivity(mContext, data.get(position));
                }
                if (view.getId() == R.id.container && data.get(position).getItemType() != DynamicBean.type_short_video) {
                    DynamicDetailsActivity.startDynamicDetailsActivity(mContext, data.get(position));
                }
                if (view.getId() == R.id.tv_location) {
                    //跳转地点列表
                    DynamicOfOnePlaceActivity.startDynamicOfOnePlaceActivity(mContext, data.get(position).getLocation());
                }
            }
        });
//        adapter.setOnTopicClickListener(new DynamicMultiItemAdapter.OnTopicClickListener() {
//            @Override
//            public void onTopicClick(String topicName) {
//                TopicDynamicActivity.startTopicDynamicActivity(mContext, topicName);
//            }
//        });
        recyclerView.setAdapter(adapter);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                adjustAtciveItem();
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // long time = System.currentTimeMillis();
                if (dx == 0 && dy == 0) {
                    return;
                }
                if (dy < 0) {
                    isDown = true;
                } else if (dy > 0) {
                    isDown = false;
                }
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (firstVisibleItemPosition < 0 || lastVisibleItemPosition < 0) {
                    return;
                }
                Log.e("lzs", "222");
                View target = findActiveTarget(findActiveVideoPos(firstVisibleItemPosition, lastVisibleItemPosition), layoutManager);
                if (null != target) {
                    attachVideoViewTo(target);
                } else {
                    if (textureView != null) {
                        textureView.setVisibility(View.GONE);
                    }
                    if (controlView != null) {
                        controlView.setVisibility(View.GONE);
                    }
                }
            }

        });


        refreshLayout = findViewById(R.id.refresh_layout);
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                int[] loc = new int[2];
                refreshLayout.getLocationOnScreen(loc);
                bottom = refreshLayout.getHeight();
            }
        });
        refreshLayout.setOnMultiPurposeListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderReleased(RefreshHeader header, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int maxDragHeight) {

            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {

            }

            @Override
            public void onFooterMoving(RefreshFooter footer, boolean isDragging, float percent, int offset, int footerHeight, int maxDragHeight) {

                if (rootContainer != null) {
                    SmartRefreshLayout.LayoutParams lp = (SmartRefreshLayout.LayoutParams) rootContainer.getLayoutParams();
                    lp.bottomMargin = offset;
                    rootContainer.setLayoutParams(lp);
                }

                CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
                lp.topMargin = offset;
                appBarLayout.setLayoutParams(lp);

                //在底部加载更多的拖动时候也监听
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (firstVisibleItemPosition < 0 || lastVisibleItemPosition < 0) {
                    return;
                }
                View target = findActiveTarget(findActiveVideoPos(firstVisibleItemPosition, lastVisibleItemPosition), layoutManager);
                if (null != target) {
                    attachVideoViewTo(target);
                } else {
                    if (textureView != null) {
                        textureView.setVisibility(View.GONE);
                    }
                    if (controlView != null) {
                        controlView.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFooterReleased(RefreshFooter footer, int footerHeight, int maxDragHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int maxDragHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                loadDynamic(data.get(data.size() - 1).getMessageId());
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadDynamic("");
            }

            @Override
            public void onStateChanged(@NonNull RefreshLayout refreshLayout, @NonNull RefreshState oldState, @NonNull RefreshState newState) {

            }
        });

        refreshLayout.autoRefresh();
    }


    private void loadDynamic(String msgID) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("pageSize", String.valueOf(PAGE_SIZE));
        //params.put("pageIndex", String.valueOf(0));
        if (!TextUtils.isEmpty(msgID)) {
            params.put("messageId", msgID);
        }
        HttpUtils.get().url(coreManager.getConfig().TOPICS_DYNAMIC)
                .params(params)
                .build()
                .execute(new BaseCallback<TopicDynamicListBean>(TopicDynamicListBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TopicDynamicListBean> result) {
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        if (result.getResultCode() == 1) {
                            if (TextUtils.isEmpty(msgID)) {
                                data.clear();
                            }
                            data.addAll(result.getData().getList());
                            FrescoUtils.loadImage(ivAvatar, result.getData().getHeadImg());
                            tvName.setText("创建人:" + result.getData().creatorNickName);
                            tvCount.setText(result.getData().msgSum + "条动态");
                            adapter.notifyDataSetChanged();
                            recyclerView.setPadding(0, 0, 0, 0);
                        } else {
                            ToastUtil.showToast(mContext, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }


    /**
     * 判断哪个Item需要播放
     */
    private void adjustAtciveItem() {

        int[] loc = new int[2];
        recyclerView.getLocationOnScreen(loc);
        int top = loc[1];
        //Log.e("lzs", "  top:" + top);
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        if (firstVisibleItemPosition < 0 || lastVisibleItemPosition < 0) {
            return;
        }
        //Log.e("lzs", "firstVisibleItemPosition:" + firstVisibleItemPosition + "  lastVisibleItemPosition:" + lastVisibleItemPosition);
        //Log.e("lzs", "top:" + loc[1] + "  bottom:" + refreshLayout.getHeight());
        if (!isDown) {
            //Log.e("lzs", "手指向上滑");
            //手指向上滑
            if (data.get(firstVisibleItemPosition).getItemType() == DynamicBean.type_short_video) {
                //是视频类型
                View firstView = layoutManager.findViewByPosition(firstVisibleItemPosition);
                View ivMask = firstView.findViewById(R.id.iv_mask);
                if (ivMask != null) {
                    //判断滑动是否超出一半，是则暂停
                    ivMask.getLocationOnScreen(loc);
                    int tH = loc[1];
                    int height = ivMask.getHeight();
                    int limitHeight = top - height / 2 + 2; //限制的高度
                    if (tH < limitHeight) {
                        //Log.e("lzs", "顶部视频超一半:" + data.get(firstVisibleItemPosition).isActive() + "  firstVisibleItemPosition:" + firstVisibleItemPosition);
                        //视频划出顶部超过一半，停止播放  ，先停止顶部的，后播放底部的
                        //Log.e("lzs", "超出一半");
                        //Log.e("lzs", "手指向上滑 顶部视频超一半");
                        if (data.get(firstVisibleItemPosition).isActive()) {
                            data.get(firstVisibleItemPosition).setActive(false);
                            data.get(firstVisibleItemPosition).isPrepareing = false;
                            if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
                                //Log.e("lzs", "手指向上滑 顶部视频超一半，暂停播放");
                                MediaPlayerHelper.getInstance().pause();
                            }
                            recyclerView.post(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyItemChanged(firstVisibleItemPosition);
                                }
                            });
                        }
                    }
                    //Log.e("lzs", "tH:" + tH);
                }
            }
            if (data.get(lastVisibleItemPosition).getItemType() == DynamicBean.type_short_video) {
                //是视频类型
                View lastVisiableView = layoutManager.findViewByPosition(lastVisibleItemPosition);
                View ivMask = lastVisiableView.findViewById(R.id.iv_mask);
                if (ivMask != null) {
                    //判断滑动是否超出一半，是则播放
                    ivMask.getLocationOnScreen(loc);
                    int tH = loc[1];
                    int height = ivMask.getHeight();
                    int limitHeight = bottom - height / 2 + 1 + top; //限制的高度
                    // Log.e("lzs", "bottom:" + bottom + " limitHeight:" + limitHeight + "  tH:" + tH);
                    if (tH < limitHeight) {
                        // Log.e("lzs", "底部视频超一半");
                        //视频划出顶部超过一半，停止播放  ，先停止顶部的，后播放底部的
                        //Log.e("lzs", "超出一半");
                        //Log.e("lzs", "手指向上滑 底部视频超一半");
                        if (!data.get(lastVisibleItemPosition).isActive()) {
                            //Log.e("lzs", "手指向上滑 底部视频超一半 开始播放");
                            setActiveItem(data.get(lastVisibleItemPosition));
                            //data.get(firstVisibleItemPosition).setActive(true);
                        }
                    }
                }
            }
        } else {
            //Log.e("lzs", "手指向下滑");
            //手指向下滑
            if (data.get(firstVisibleItemPosition).getItemType() == DynamicBean.type_short_video) {
                //第一个可见的 是视频类型
                View firstView = layoutManager.findViewByPosition(firstVisibleItemPosition);
                View ivMask = firstView.findViewById(R.id.iv_mask);
                if (ivMask != null) {
                    //判断滑动是否超出一半，是则播放
                    ivMask.getLocationOnScreen(loc);
                    int tH = loc[1];
                    int height = ivMask.getHeight();
                    int limitHeight = top - height / 2 - 2; //限制的高度
                    if (tH > limitHeight) {
                        //视频划出顶部超过一半,播放
                        //Log.e("lzs", "手指向下滑 顶部视频超一半");
                        if (!data.get(firstVisibleItemPosition).isActive()) {
                            // Log.e("lzs", "手指向下滑 顶部视频超一半，开始播放");
                            setActiveItem(data.get(firstVisibleItemPosition));
                        }
                    }
                    // Log.e("lzs", "tH:" + tH);
                }
            }
            if (data.get(lastVisibleItemPosition).getItemType() == DynamicBean.type_short_video) {
                //是视频类型
                View lastVisiableView = layoutManager.findViewByPosition(lastVisibleItemPosition);
                View ivMask = lastVisiableView.findViewById(R.id.iv_mask);
                if (ivMask != null) {
                    //判断滑动是否超出一半，是则停止
                    ivMask.getLocationOnScreen(loc);
                    int tH = loc[1];
                    int height = ivMask.getHeight();
                    int limitHeight = bottom - height / 2 + 1 + top; //限制的高度
                    // Log.e("lzs", "bottom:" + bottom + " limitHeight:" + limitHeight + "  tH:" + tH);
                    if (tH > limitHeight) {
                        // Log.e("lzs", "底部视频超一半");
                        //视频划出顶部超过一半，停止播放  ，先停止顶部的，后播放底部的
                        //Log.e("lzs", "手指向下滑 底部视频超一半");
                        if (data.get(lastVisibleItemPosition).isActive()) {
                            data.get(lastVisibleItemPosition).setActive(false);
                            data.get(lastVisibleItemPosition).isPrepareing = false;
                            if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
                                //Log.e("lzs", "手指向下滑 底部视频超一半，暂停播放");
                                MediaPlayerHelper.getInstance().pause();
                            }
                            recyclerView.post(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyItemChanged(lastVisibleItemPosition);
                                }
                            });
                        }
                    }
                }
            }
            // Log.e("lzs", "firstVisibleItemPosition>" + firstVisibleItemPosition);
        }
        //Log.e("lzs", "onScrolled  dx:" + dx + "   dy:" + dy);
        DynamicBean newBean = findActiveVideoDynamicBean(firstVisibleItemPosition, lastVisibleItemPosition);
        //playingVideoDynamicBean = findActiveVideoDynamicBean(firstVisibleItemPosition, lastVisibleItemPosition);
        View target = findActiveTarget(findActiveVideoPos(firstVisibleItemPosition, lastVisibleItemPosition), layoutManager);
        //Log.e("lzs", "newBean :" + newBean);
        if (null != target) {
            if (newBean != null && !newBean.isPrepareing) {
                if (playingVideoDynamicBean != null && playingVideoDynamicBean != newBean) {
                    playingVideoDynamicBean = newBean;
                    playingVideoDynamicBean.isPrepareing = true;
                    //没有开始播放，初始化 textureview 启动播放
                    addVideoView();
                } else if (playingVideoDynamicBean == null) {
                    playingVideoDynamicBean = newBean;
                    addVideoView();
                } else if (playingVideoDynamicBean == newBean) {
                    playingVideoDynamicBean.setActive(true);
                    playingVideoDynamicBean.isPrepareing = true;
                    if (textureView != null) {
                        textureView.setVisibility(View.VISIBLE);
                    }
                    if (controlView != null) {
                        controlView.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyItemChanged(adapter.getParentPosition(playingVideoDynamicBean));
                    MediaPlayerHelper.getInstance().start();
                }
            } else {

            }
            attachVideoViewTo(target);
        } else {
            if (textureView != null) {
                textureView.setVisibility(View.GONE);
            }
            if (controlView != null) {
                controlView.setVisibility(View.GONE);
            }
        }
        // Log.e("lzs", "time:" + (System.currentTimeMillis() - time));
    }


    private void setActiveItem(DynamicBean dynamicBean) {
        if (null == dynamicBean) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            if (dynamicBean == data.get(i)) {
                dynamicBean.setActive(true);
                adapter.notifyItemChanged(i);
            } else if (data.get(i).isActive()) {
                data.get(i).setActive(false);
                data.get(i).isPrepareing = false;
                adapter.notifyItemChanged(i);
            }
        }
    }


    private ConstraintLayout initVideoView() {
        videoView = (ConstraintLayout) LayoutInflater.from(mContext).inflate(R.layout.layout_videoview, null);
        textureView = videoView.findViewById(R.id.textureView);
        textureView.setSurfaceTextureListener(this);
        controlView = videoView.findViewById(R.id.view_controll);
        controlView.setController(this);
        return videoView;
    }

    private View findActiveTarget(int activePos, RecyclerView.LayoutManager layoutManager) {
        // Log.e("lzs", "activePos:" + activePos);
        View view = layoutManager.findViewByPosition(activePos);
        if (view == null) {
            return null;
        }
        View ivMask = view.findViewById(R.id.iv_mask);
        if (ivMask != null) {
            return ivMask;
        }
        return null;
    }

    /**
     * textureview 依附在 active 的列表item上
     *
     * @param target
     */
    private void attachVideoViewTo(View target) {
        if (videoView == null || !videoView.isAttachedToWindow()) {
            return;
        }
        videoView.setVisibility(target.getVisibility());
        int[] location = new int[2];
        int height = target.getHeight();
        int width = target.getWidth();
        target.getLocationOnScreen(location);
        CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) videoView.getLayoutParams();
        lp.height = height;
        lp.width = width;
        videoView.setLayoutParams(lp);
        //Log.e("lzs", "x:" + location[0] + "  y:" + location[1]);
        move(videoView, location[0], location[1]);
        // DynamicShortVideoControlView controlView = videoView.findViewById(R.id.view_controll);
        //Log.e("lzs", "controlView w:" + controlView.getWidth() + "  controlView h:" + controlView.getHeight());
    }

    private void move(View source, int toX, int toY) {
        int[] loc = new int[2];
        recyclerView.getLocationOnScreen(loc);
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) source.getLayoutParams();
        lp.topMargin = toY;
        //Log.e("lzs", "lp.topMargin:" + lp.topMargin);
        lp.leftMargin = toX;
        source.setLayoutParams(lp);
    }


    private DynamicBean findActiveVideoDynamicBean(int firstVisiableItemPos, int lastVisiableItemPos) {
        for (int i = firstVisiableItemPos; i <= lastVisiableItemPos; i++) {
            if (data.get(i).getItemType() == DynamicBean.type_short_video && data.get(i).isActive()) {
                return data.get(i);
            }
        }
        return null;
    }

    private int findActiveVideoPos(int firstVisiableItemPos, int lastVisiableItemPos) {
        for (int i = firstVisiableItemPos; i <= lastVisiableItemPos; i++) {
            if (data.get(i).getItemType() == DynamicBean.type_short_video && data.get(i).isActive()) {
                return i;
            }
        }
        return -1;
    }

    private void setVoiceState(List<DynamicBean> list) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getItemType() == DynamicBean.type_short_video) {
                if (list.get(i).getBody().getVideos() == null || list.get(i).getBody().getVideos().size() == 0) {
                    continue;
                }
                list.get(i).getBody().getVideos().get(0).setSilent(MediaPlayerHelper.getInstance().getSilentRecord(list.get(i).getBody().getVideos().get(0).getOriginalUrl()));
            }
        }
    }


    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onVideoSizeChanged(IMediaPlayer mp, int width, int height) {
        Log.e("lzs", "onVideoSizeChanged: width  " + width + "  height:" + height);
        if (playingVideoDynamicBean == null) {
            return;
        }
        playingVideoDynamicBean.setVideoHeight(height);
        playingVideoDynamicBean.setVideoWidth(width);
    }

    @Override
    public void onSeekComplete(IMediaPlayer mp) {

    }

    @Override
    public void onBufferingUpdate(IMediaPlayer mp, int percent) {
        if (controlView != null) {
            controlView.showLoading();
        }
        if (percent - 100 < 10) {
            if (controlView != null) {
                controlView.hideLoading();
            }
            if (textureView != null) {
                textureView.setVisibility(View.VISIBLE);
            }
        } else {
            if (textureView != null) {
                textureView.setVisibility(View.INVISIBLE);
            }
        }
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        return false;
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {

    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        startProgressUpdateTimer();
    }


    private void setVoiceIconState(boolean isSilent) {
        controlView.setVoiceIconState(isSilent);
    }

    @Override
    public void onVoiceClick(ImageView imageView) {
        if (playingVideoDynamicBean.getBody().getVideos() == null || playingVideoDynamicBean.getBody().getVideos().size() == 0) {
            return;
        }
        String url = playingVideoDynamicBean.getBody().getVideos().get(0).getOriginalUrl();
        if (MediaPlayerHelper.getInstance().getSilentRecord(url)) {
            //开启声音
            //没有设置音量,开启声音
            MediaPlayerHelper.getInstance().playUnSilent(url);
        } else {
            //静音播放
            MediaPlayerHelper.getInstance().playSilently(url);
        }
        boolean iSilent = MediaPlayerHelper.getInstance().getSilentRecord(url);
        setVoiceIconState(iSilent);
        playingVideoDynamicBean.getBody().getVideos().get(0).setSilent(iSilent);
        adapter.notifyItemChanged(data.indexOf(playingVideoDynamicBean));
    }

    @Override
    public void onPauseClick(ImageView imageView) {

    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        //Log.e("lzs", "onSurfaceTextureAvailable：" + surface);
        surfaceTexture = surface;
        if (controlView != null) {
            controlView.setVisibility(View.VISIBLE);
        }
        if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
            MediaPlayerHelper.getInstance().pause();
        }

        //没有开始播放，初始化 textureview 启动播放
        preparePlay();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
        if (playingVideoDynamicBean.getBody().getVideos() == null || playingVideoDynamicBean.getBody().getVideos().size() == 0) {
            return;
        }
        String url = playingVideoDynamicBean.getBody().getVideos().get(0).getOriginalUrl();
        if (MediaPlayerHelper.getInstance().getSilentRecord(url)) {
            //  Log.e("lzs","静音");
        } else {
            //Log.e("lzs","非静音");
            MediaPlayerHelper.getInstance().playUnSilent(url);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        adapter.onPause();
        if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_playing) {
            MediaPlayerHelper.getInstance().pause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MediaPlayerHelper.getInstance().setMediaPlayerHelperListener(this);
        if (MediaPlayerHelper.getInstance().getPlayerState() == MediaPlayerHelper.state_pause) {
            MediaPlayerHelper.getInstance().start();
        }
    }


    public static class TopicDynamicListBean {

        private String headImg;
        private String creatorNickName;
        private int msgSum;
        private List<DynamicBean> list;

        public TopicDynamicListBean() {

        }

        public String getHeadImg() {
            return headImg;
        }

        public void setHeadImg(String headImg) {
            this.headImg = headImg;
        }

        public String getCreatorNickName() {
            return creatorNickName;
        }

        public void setCreatorNickName(String creatorNickName) {
            this.creatorNickName = creatorNickName;
        }

        public int getMsgSum() {
            return msgSum;
        }

        public void setMsgSum(int msgSum) {
            this.msgSum = msgSum;
        }

        public List<DynamicBean> getList() {
            return list;
        }

        public void setList(List<DynamicBean> list) {
            this.list = list;
        }
    }

}
